package com.example.king.myapplication;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;


public class MainActivity extends Activity {

    //所有要显示的图片资源索引
    private static final Integer[] imagelist = {R.drawable.img1,
            R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5,
            R.drawable.img6, R.drawable.img7, R.drawable.img8,};
    //创建ImageSwitcher对象;
    private ImageSwitcher imageSwitcher;
    // 索引
    private static int index = 0;
    private Button buttonS;
    private Button buttonX;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //初始化控件
        buttonS = (Button) findViewById(R.id.button_S);
        buttonX = (Button) findViewById(R.id.button_X);
        imageSwitcher = (ImageSwitcher) findViewById(R.id.image_list);

        //imageSwticher必须设置一个viewfactory后才可以查看图片
        imageSwitcher.setFactory(new ImageViewFactory(this));
        //设置图片资源id
        imageSwitcher.setBackgroundResource(imagelist[index]);


    }

    public void clicklast(View view) {
        if (index >= 0 && index < imagelist.length - 1) {
            index++;
            imageSwitcher.setBackgroundResource(imagelist[index]);
        } else {
            index = imagelist.length - 1;
        }
    }

    public void clicknext(View view) {
        if (index > 0 && index < imagelist.length) {
            index--;
            imageSwitcher.setBackgroundResource(imagelist[index]);
        } else {
            index = imagelist.length - 1;
        }
    }

    class ImageViewFactory implements ViewSwitcher.ViewFactory {
        private Context context;

        public ImageViewFactory(Context context) {
            this.context = context;
        }

        @Override
        public View makeView() {
            //定义每个图像的显示大小
            ImageView iv = new ImageView(this.context);
            iv.setLayoutParams(new ImageSwitcher.LayoutParams(300, 300));
            return iv;
        }
    }


}